﻿using System.Linq;
using Telerik.OpenAccess;
using SampleWebApplication.Data.Models;

namespace SampleWebApplication.Data
{
    public class DataManager
    {
        // ---------------------------------------------------------------------
        // Contacts
        // ---------------------------------------------------------------------

        public IQueryable<Contact> GetContacts()
        {
            var query = from c in Scope.Extent<Contact>()
                        select c;

            return query;
        }

        public void AddContact(string firstName, string lastName, Department department)
        {
            var contact = new Contact();
            contact.FirstName = firstName;
            contact.LastName = lastName;
            contact.Department = department;
            AddContact(contact);
        }

        public void AddContact(Contact contact)
        {
            Scope.Add(contact);
            Scope.Transaction.Commit();
        }

        // ---------------------------------------------------------------------
        // Departments
        // ---------------------------------------------------------------------

        public IQueryable<Department> GetDepartments()
        {
            var query = from c in Scope.Extent<Department>()
                        select c;

            return query;
        }

        public void AddDepartment(string departmentName)
        {
            var department = new Department();
            department.Name = departmentName;
            AddDepartment(department);
        }

        public void AddDepartment(Department department)
        {
            Scope.Add(department);
            Scope.Transaction.Commit();
        }

        public Department GetDepartment(string departmentName)
        {
            var query = from d in Scope.Extent<Department>()
                        where d.Name == departmentName
                        select d;

            return query.First();
        }

        // ---------------------------------------------------------------------
        // Scope
        // ---------------------------------------------------------------------

        public IObjectScope Scope
        {
            get
            {
                return DataScope.Get();
            }
        }
    }
}
